class PubSub {
  private events: { [key: string]: ((data: any) => void)[] } = {};

  // 订阅事件（返回取消订阅函数）
  subscribe(event: string, callback: (data: any) => void): () => void {
    if (typeof event !== "string" || event.trim() === "") {
      throw new Error("Event name must be a non-empty string");
    }
    if (!this.events[event].includes(callback)) {
      (this.events[event] || (this.events[event] = [])).push(callback);
    }
    // 返回取消订阅函数
    return () => this.unsubscribe(event, callback);
  }

  // 发布事件
  publish(event: string, data: any): void {
    if (typeof event !== "string" || event.trim() === "") {
      throw new Error("Event name must be a non-empty string");
    }
    this.events[event]?.forEach((cb) => cb(data));
  }

  // 取消订阅（提供两种方式）
  unsubscribe(event: string, callback?: (data: any) => void): void {
    if (typeof event !== "string" || event.trim() === "") {
      throw new Error("Event name must be a non-empty string");
    }
    if (this.events[event]) {
      if (callback) {
        // 移除特定回调
        const index = this.events[event].indexOf(callback);
        if (index !== -1) {
          this.events[event].splice(index, 1);
        }
        // 清理空数组
        if (this.events[event].length === 0) {
          delete this.events[event];
        }
      } else {
        // 移除该事件所有回调
        delete this.events[event];
      }
    }
  }
}

const bus = new PubSub();

export default bus;
